package com.zoe.app.aspect;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zoe.app.annotation.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author zoe.Zhang
 * @date 2023/01/30
 * @description
 */
@Aspect
@Component
@Slf4j
public class LogAspect {
    @Around(value = "@annotation(logs)")
    public Object around(ProceedingJoinPoint point, Log logs) throws Throwable {
        Object proceed = null;
        try {
            log.info("环绕前通知 \n");
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            Log annotation = AnnotationUtil.getAnnotation(method, Log.class);
            if (ObjectUtil.isNotNull(annotation)) {
                System.out.println(annotation.name());
            }
            proceed = point.proceed();
            log.info("环绕后通知 \n");
            int i = 1 / 0;
            return proceed;
        }
        catch (Throwable e) {
            // 如果不抛出异常，那么就会导致事务方法失效，全局异常也无法获取到，可以根据实际情况决定是否抛出异常。
            throw e;
        }
    }
}
